<template>
  <el-row style="margin-top:50px">
    <el-col :span="18">
      <el-form
        label-width="350px"
        :model="shopInfo"
        :rules="rules"
        ref="shopRef"
      >
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="shopInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-autocomplete
            popper-class="my-autocomplete"
            v-model="shopInfo.address"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            style="width:100%"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }}</div>
              <span class="addr">{{ item.address }}</span>
            </template>
          </el-autocomplete>
          <span>当前城市:{{ city.name }}</span>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model.number="shopInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="店铺简介">
          <el-input v-model="shopInfo.description"></el-input>
        </el-form-item>
        <el-form-item label="店铺标语">
          <el-input v-model="shopInfo.promotion_info"></el-input>
        </el-form-item>
        <el-form-item label="店铺分类">
          <el-cascader
            clearable
            v-model="shopKindsValue"
            :options="shopKindsOptions"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="食品特点">
          <el-form-item>
            <span>品牌保证</span>
            <el-switch
              v-model="shopInfo.is_premium"
              active-color="#13ce66"
              inactive-color="#BBCBD9"
            >
            </el-switch>
            <span>蜂鸟专送</span>
            <el-switch
              v-model="shopInfo.delivery_mode"
              active-color="#13ce66"
              inactive-color="#BBCBD9"
            >
            </el-switch>
            <span>新开店铺</span>
            <el-switch
              v-model="shopInfo.new"
              active-color="#13ce66"
              inactive-color="#BBCBD9"
            >
            </el-switch>
          </el-form-item>
          <el-form-item>
            <span>外卖保</span>
            <el-switch
              v-model="shopInfo.bao"
              active-color="#13ce66"
              inactive-color="#BBCBD9"
            >
            </el-switch>
            <span>准时达</span>
            <el-switch
              v-model="shopInfo.zhun"
              active-color="#13ce66"
              inactive-color="#BBCBD9"
            >
            </el-switch>
            <span>开发票</span>
            <el-switch
              v-model="shopInfo.piao"
              active-color="#13ce66"
              inactive-color="#BBCBD9"
            >
            </el-switch>
          </el-form-item>
        </el-form-item>
        <el-form-item label="配送费">
          <el-input-number
            size="medium"
            v-model="shopInfo.float_delivery_fee"
            :min="1"
            :max="20"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="起送价">
          <el-input-number
            size="medium"
            v-model="shopInfo.float_minimum_order_amount"
            :min="10"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="营业时间">
          <el-time-select
            placeholder="起始时间"
            v-model="shopInfo.startTime"
            :picker-options="{
              start: '05:30',
              step: '00:15',
              end: '23:30'
            }"
          >
          </el-time-select>
          <el-time-select
            align="right"
            placeholder="结束时间"
            v-model="shopInfo.endTime"
            :picker-options="{
              start: '05:30',
              step: '00:15',
              end: '23:30',
              minTime: shopInfo.startTime
            }"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="上传头像">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/v1/addimg/shop"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="shopInfo.image_path"
              :src="shopInfo.image_path"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传营业执照">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/v1/addimg/shop"
            :show-file-list="false"
            :on-success="handleBusinessSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="shopInfo.business_license_image"
              :src="shopInfo.business_license_image"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传餐饮服务许可证">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/v1/addimg/shop"
            :show-file-list="false"
            :on-success="handleServiceSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="shopInfo.catering_service_license_image"
              :src="shopInfo.catering_service_license_image"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="优惠活动">
          <el-select v-model="activityValue" placeholder="" @change="open">
            <el-option
              :value="item.value"
              :label="item.label"
              v-for="(item, index) in options"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-row style="text-algin:center">
          <el-table
            border=""
            :data="activitiesArray"
            style="margin-left:300px;width:50%;"
            header-cell-class-name="headerClass"
          >
            <el-table-column prop="icon_name" label="活动名称" width="100">
            </el-table-column>
            <el-table-column prop="name" label="活动标题" width="100">
            </el-table-column>
            <el-table-column prop="description" label="活动详情">
            </el-table-column>
            <el-table-column prop="prop" label="操作" width="100">
              <template slot-scope="{ row, $index }">
                <HintButton
                  title="删除"
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  @click="deleteActivity($index)"
                ></HintButton>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-form-item style="margin:40px 0" label-width="500px">
          <template slot-scope="{ row, $index }">
            <el-button type="primary" @click="createShop">立即创建</el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
export default {
  name: "addmerchant",
  data() {
    return {
      city: {
        pinyin: "beijing",
        is_map: true,
        longitude: 116.407173,
        latitude: 39.90469,
        sort: 2000,
        area_code: "010",
        abbr: "BJ",
        name: "北京",
        id: 3
      },
      shopInfo: {
        name: "", //店铺名称
        address: "", //地址
        phone: "",
        latitude: "",
        longitude: "",
        description: "", //介绍
        promotion_info: "", //店铺标语
        float_delivery_fee: 5, //运费
        float_minimum_order_amount: 20, //起价
        is_premium: true, //品牌商铺,默认false
        delivery_mode: true, //支持蜂鸟专送，默认false
        new: true, //新开店铺，默认false
        bao: true, //支持保险，默认false
        zhun: true, //准时达，默认false
        piao: true, //开发票，默认false
        startTime: "", //开始营业时间
        endTime: "", //停止营业时间
        image_path: "", //店铺图片地址
        business_license_image: "", //营业执照图片地址
        catering_service_license_image: "" //餐饮服务许可证图片地址
      },
      /* 表单验证 */
      rules: {
        name: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "change" }],
        phone: [
          { required: true, message: "请输入手机号码" },
          { type: "number", message: "手机号必须是数字" }
        ]
      },
      //商铺分类value和options一样
      shopKindsValue: ["小吃夜宵", "烧烤"],
      shopKindsOptions: [],
      //活动分类及详情表格
      activityValue: "满减优惠",
      options: [
        {
          value: "满减优惠",
          label: "满减优惠"
        },
        {
          value: "优惠大酬宾",
          label: "优惠大酬宾"
        },
        {
          value: "新用户立减",
          label: "新用户立减"
        },
        {
          value: "进店领券",
          label: "进店领券"
        }
      ],
      activitiesArray: [
        {
          icon_name: "减",
          name: "满减优惠",
          description: "满50减20"
        }
      ]
    };
  },
  mounted() {
    this.initCityShopData();
    // this.$API.addmerchant.reqGuessLocation();
  },
  methods: {
    /* 活动详情添加 */
    open() {
      this.$prompt("请输入活动详情", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          if (value) {
            const icon_name = this.activityValue.slice(0, 1);
            const obj = {
              icon_name,
              name: this.activityValue,
              description: value
            };
            this.activitiesArray.push(obj);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    /* 初始化城市列表和食品分类 */
    async initCityShopData() {
      try {
        let shopKinds = await this.$API.addmerchant.reqShopKindsList();
        //城市定位
        // this.city = await this.$API.addmerchant.reqGuessLocation("guess");
        // console.log(shopKinds);
        shopKinds.splice(7, 1);
        /* 初始化商品分类 */
        let shopKindsOptions = [];
        if (shopKinds.length > 0) {
          shopKinds.forEach(item => {
            const bigItemObj = {
              value: item.name,
              label: item.name,
              children: []
            };
            if (item.sub_categories.length > 0) {
              item.sub_categories.forEach(item1 => {
                const childObj = {
                  value: item1.name,
                  label: item1.name
                };
                bigItemObj.children.push(childObj);
              });
            }
            shopKindsOptions.push(bigItemObj);
          });
        }
        this.shopKindsOptions = shopKindsOptions;
      } catch (error) {
        this.$message.success(error);
      }
    },
    //处理城市搜索
    async querySearch(queryString, cb) {
      // console.log(queryString);
      if (queryString.trim()) {
        const dimSearchList = await this.$API.addmerchant.reqSearchAddress(
          3,
          queryString.trim()
        );
        cb(dimSearchList);
      }
    },
    //模糊搜索选中处理回调
    handleSelect(item) {
      this.shopInfo.address = item.address;
      this.shopInfo.latitude = item.latitude;
      this.shopInfo.longitude = item.longitude;
    },
    /* 用户头像,三个图片回调及上传前的回调 */
    handleAvatarSuccess(res, file) {
      this.shopInfo.image_path = "https://elm.cangdu.org/img/" + res.image_path;
    },
    handleBusinessSuccess(res, file) {
      this.shopInfo.business_license_image =
        "https://elm.cangdu.org/img/" + res.image_path;
    },
    handleServiceSuccess(res, file) {
      this.shopInfo.catering_service_license_image =
        "https://elm.cangdu.org/img/" + res.image_path;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /* 删除活动详情表格 */
    deleteActivity(index) {
      this.activitiesArray.splice(index, 1);
    },
    /* 创建商铺 */
    createShop() {
      // const { activitiesArray, shopKindsValue, shopInfo } = this;
      // console.log(shopKindsValue.join("/"));
      this.$refs.shopRef.validate(async valid => {
        if (valid) {
          const { activitiesArray, shopKindsValue, shopInfo } = this;
          console.log(shopKindsValue);
          Object.assign(
            this.shopInfo,
            { activities: activitiesArray },
            { category: shopKindsValue.join("/") }
          );
          try {
            const result = await this.$API.addmerchant.reqAddShop(
              this.shopInfo
            );

            if (result.status === 1) {
              this.$message.success("添加商铺成功");
              this.shopInfo = {
                name: "", //店铺名称
                address: "", //地址
                phone: "",
                latitude: "",
                longitude: "",
                description: "", //介绍
                promotion_info: "", //店铺标语
                float_delivery_fee: 5, //运费
                float_minimum_order_amount: 20, //起价
                is_premium: true, //品牌商铺,默认false
                delivery_mode: true, //支持蜂鸟专送，默认false
                new: true, //新开店铺，默认false
                bao: true, //支持保险，默认false
                zhun: true, //准时达，默认false
                piao: true, //开发票，默认false
                startTime: "", //开始营业时间
                endTime: "", //停止营业时间
                image_path: "", //店铺图片地址
                business_license_image: "", //营业执照图片地址
                catering_service_license_image: "" //餐饮服务许可证图片地址
              };
            } else {
              this.$message.error(result.message);
            }
          } catch (error) {
            this.$message.warning(error.message);
          }
        } else {
          this.$message.error("输入信息有误");
          return false;
        }
      });
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
.el-table .headerClass {
  background-color: #edf1f6;
}
</style>
